import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from "@/components/Login";
import Home from "@/components/Home";
import Welcome from "@/components/Welcome";
import UserList from "@/components/admin/UserList";

Vue.use(VueRouter)

const routes = [
  {
    path:"/",
    redirect:"/login"
  },
  {
    path: "/login",
    component:Login
  },
  {
    path: "/home",
    component: Home,
    redirect: "/welcome",
    children:[
      {path:"/welcome",component:Welcome},
      {path: "/user",component: UserList}
    ]
  },
]

const router = new VueRouter({
  routes
})

router.beforeEach((to,from,next)=>{
  // to 将要访问
  // from 从那访问
  // next 接着干的事 next（）
  if (to.path=='/login') return next();
  // 获取user
  const userFlag = window.sessionStorage.getItem("user");
  if (!userFlag) return next('/login');  // 无值返回登录页
  next(); // 符合要求
})

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location,onResolve,onReject){
  if (onResolve || onReject) return originalPush.call(this,location,onReject)
  return originalPush.call(this,location).catch(err=>err)
}

export default router
